package tur.br.moradadosol.view.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import tur.br.moradadosol.control.LoginControl;
import tur.br.moradadosol.control.UserAutentication;
import tur.br.moradadosol.model.Usuario;
import tur.br.moradadosol.view.form.LoginForm;

public class LoginAction extends Action {

	public ActionForward execute(
			ActionMapping mapping, 
			ActionForm form,
			HttpServletRequest request, 
			HttpServletResponse response)
			throws Exception {
		
		ActionMessages errors = new ActionMessages();
		
		LoginForm loginForm = (LoginForm)form;
		
		LoginControl control = new LoginControl();
		
		if(loginForm.getBtnSubmit().length() > 0) {
			
			try {
				Usuario usuarioAutenticado = control.autenticarUsuario(
						loginForm.getObjUsuario());
				
				UserAutentication.setUserAutenticated(request.getSession(), 
						usuarioAutenticado);
				
				return mapping.findForward("home");
			}
			catch (Exception e) {
				
				loginForm.getObjUsuario().setSenha("");
				
				errors.add("login.error", 
						new ActionMessage(e.getMessage()));
				if(!e.getMessage().startsWith("error")) 
					throw e;
				
				saveErrors(request, errors);
			}
		}
		
		return mapping.getInputForward();
	}
	
	
}
